package com.itany.controller;

import com.alibaba.fastjson.JSON;
import com.itany.utils.SFTPUtils;
import com.itany.vo.UeditorResult;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/ueditor/controller")
public class UeditorController {

    @Value("classpath:config.json")
    private Resource  configFile;

    @RequestMapping(value = "",params = "action=config")
    @ResponseBody
    public Object loadConfig()throws Exception{
        String jsonStr = FileUtils.readFileToString(configFile.getFile());
        // System.out.println(jsonStr);
        return JSON.parse(jsonStr);

    }

    @RequestMapping(value = "",params = "action=uploadimage")
    @ResponseBody
    public UeditorResult uploadimage(MultipartFile upfile, HttpServletRequest request)throws Exception{
        String fileName = upfile.getOriginalFilename();
        fileName=System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String  uploadDir ="yzy/" +dateFormat.format(new Date())+"/";

        SFTPUtils.sftpPut("192.168.4.8","tyh","123",22,uploadDir,upfile.getInputStream(),fileName);
        return UeditorResult.success("http://192.168.4.8:8080/"+uploadDir+fileName,"成功");

    }
}
